#!/usr/bin/env python
# -*- coding: utf-8 -*-

import psycopg2
from configparser import ConfigParser

def get_db_config():
    """读取数据库配置"""
    config = ConfigParser()
    config.read('table/db_config.ini', encoding='utf-8')
    return {
        'host': config.get('postgresql', 'HOST'),
        'port': config.getint('postgresql', 'PORT'),
        'database': 'QA_knowledge',
        'user': config.get('postgresql', 'USER_NAME'),
        'password': config.get('postgresql', 'PASSWD')
    }

def check_table():
    """检查特定表名"""
    
    db_config = get_db_config()
    target_name = "大伙房水库水文自动测报系统测站汇总表"
    
    try:
        conn = psycopg2.connect(**db_config)
        cursor = conn.cursor()
        
        print("=" * 80)
        print(f"查找表名: {target_name}")
        print(f"表名长度: {len(target_name)}")
        print("=" * 80)
        
        # 精确匹配
        cursor.execute("""
            SELECT table_name, table_title, LENGTH(table_name)
            FROM table_images
            WHERE table_name = %s
        """, (target_name,))
        
        result = cursor.fetchone()
        if result:
            print(f"✅ 精确匹配找到:")
            print(f"   table_name: {result[0]}")
            print(f"   table_title: {result[1]}")
            print(f"   长度: {result[2]}")
        else:
            print(f"❌ 精确匹配未找到")
            
            # 模糊匹配
            print("\n尝试模糊匹配（LIKE）:")
            cursor.execute("""
                SELECT table_name, table_title, LENGTH(table_name)
                FROM table_images
                WHERE table_name LIKE %s
            """, (f"%{target_name}%",))
            
            results = cursor.fetchall()
            if results:
                print(f"找到 {len(results)} 条相似记录:")
                for r in results:
                    print(f"   - {r[0]} (长度: {r[2]})")
            else:
                print("   未找到相似记录")
                
            # 查看所有包含"水文自动测报系统"的记录
            print("\n查找所有包含'水文自动测报系统'的记录:")
            cursor.execute("""
                SELECT table_name, LENGTH(table_name)
                FROM table_images
                WHERE table_name LIKE %s
            """, ("%水文自动测报系统%",))
            
            results = cursor.fetchall()
            if results:
                print(f"找到 {len(results)} 条记录:")
                for r in results:
                    print(f"   - '{r[0]}' (长度: {r[1]})")
                    # 打印字符对比
                    if '汇总' in r[0] or '测站' in r[0]:
                        print(f"     目标: '{target_name}'")
                        print(f"     实际: '{r[0]}'")
                        print(f"     相等: {r[0] == target_name}")
            else:
                print("   未找到任何相关记录")
        
        cursor.close()
        conn.close()
        
    except Exception as e:
        print(f"\n❌ 错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    check_table()

